<template>
	<view v-if="isShowWebView">

		<web-view  ref="webView" :src="webviewPath" @message="onMessage"
			class="webview"></web-view>
		<view class="bottomBtnContainer">
			<view class="bottomBtnWrapper" @click="captureWebview">
				截屏并打开抖音扫一扫
			</view>
		</view>
<!-- 		<view class="bottomBtnContainer">
			<view class="bottomBtnWrapper" @click="gotoAuthTiktok">
				截屏并打开抖音扫一扫
			</view>
		</view> -->
	</view>
</template>

<script>
	const api = require("@/static/js/api.js")
	const utils = require("@/static/js/utils.js")
	const config = require("@/config.js")
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex';
	let that = null
	let systemInfo = uni.getSystemInfoSync();
	// #ifdef APP-PLUS
	var plugin = uni.requireNativePlugin('Vnidev-DyPlugin-Core')
	const dyclientId = config.tiktokClientKeyApp;
	// #endif
	export default {
		data() {
			return {
				webviewPath: "",
				ws: null,
				bitmap: null,
				isShowWebView: true,
				image: '', //截图
			};
		},

		computed: {
			...mapState({
				hasLogin: state => state.userInfo.hasLogin,
				isAuthPhone: state => state.userInfo.isAuthPhone,
				isAuthUserInfo: state => state.userInfo.isAuthUserInfo,
				isSeller: state => state.userInfo.isSeller,
				sellerObj: state => state.userInfo.sellerObj,
				buyerObj: state => state.userInfo.buyerObj,
				shopInfo: state => state.userInfo.shopInfo,

				appAvatar: state => state.userInfo.appAvatar,
				appNickName: state => state.userInfo.appNickName,
				authTiktokInfo: state => state.userInfo.authTiktokInfo,
				authTiktokPermission: state => state.userInfo.authTiktokPermission,
			}),
		},

		onLoad(options) {
			that = this;
			// #ifdef APP-PLUS
			plus.navigator.setUserAgent({
				"value": "CustomUA",
				"concatenate": true			
			})
			// #endif

			// const webview = this.$refs.webView.$el;

			// // 修改User-Agent
			// webview.addEventListener("loadstart", () => {
			// 	webview.evaluateJavaScript(
			// 		`navigator.userAgent = "your-useragent";`,
			// 		() => {}
			// 	);
			// });

			var obj = {
				userId: this.buyerObj.id,
				tenantCode: uni.getStorageSync("projectId")
			}
			// var clientKey = "awajgvfds51v06mn" //梦维营销云
			// var clientKey = "awui063l9x35pnwf" //梦维营销WEB
			// var clientKey = "awjp33hvpj8yo95h" //梦维营销测试
			var clientKey = config.tiktokClientKeyWeb;
			var url = "https://open.douyin.com/platform/oauth/connect?response_type=code"
			var state = encodeURIComponent(JSON.stringify(obj))
			// var scope = "user_info,data.external.item,trial.whitelist"
			var scope = "user_info,video.list.bind,data.external.item"
			var redirectUri =  config.service.redirectUriTiktokAuth  //"https://etalk-test.fzzkzh.com/api/douyin/auth"//"https://40001.fzzkzh.com/douyin/auth"
			this.webviewPath = `${url}&client_key=${clientKey}&scope=${scope}&redirect_uri=${redirectUri}&state=${state}`
			// this.webviewPath = "https://etalk.fzzkzh.com/message.html"
			// this.webviewPath = "http://192.168.0.55:8081/test.html"
			// this.createBtn()
		},
		onReady() {
			// #ifdef APP-PLUS
			let _this = this
			console.log("systemInfo", systemInfo)

			var webviewHeight = systemInfo.windowHeight - uni.upx2px(250)
			var navHeight = systemInfo.screenHeight - systemInfo.windowHeight
			// 获取当前Webview窗口对象
			const ws = plus.webview.currentWebview();
			// this.ws = ws
			var currentWebview = this.$scope.$getAppWebview()
			setTimeout(function() {
				let wv = currentWebview.children()[0];
				_this.ws = wv
				_this.ws.setStyle({
					top: navHeight,
					height: webviewHeight
				})
			}, 1000); //如果是页面初始化调用时，需要延时一下 
			// #endif
		},


		onShow() {
			
		},
		methods: {
			...mapMutations(['setUserInfo', 'setLoginStatus', 'setUserId', "setOrigin"]),

			createBtn() {
				let robotView = new plus.nativeObj.View('robot-btn', {
						bottom: '0px',
						left: '39%',
						height: '44px',
						width: '100px'
					},
					[{
							tag: 'img',
							id: 'robot',
							src: '/static/image/bg_home.jpg',
							position: {
								top: '0px',
								left: '0px',
								width: '68px',
								height: '28px'
							}
						},

					]);
				robotView.show();
				robotView.addEventListener("click", (e) => {
					console.log("robotView")
				}, false);

			},

			onMessage(e) {
				console.log("@@@@@@@onMessage",e)
				for (var i in e.detail.data){
					var item = e.detail.data[i]
					if (item&&item.action&&item.action=='success'){
						that.isShowWebView = false;
						that.getUserInfo()
					}
					if (item&&item.action&&item.action=='error'){
						uni.showToast({
							icon: "none",
							title: "对不起, 你抖音号已被其他项目绑定!",
							duration: 3000,
						})
						that.isShowWebView = false;
						setTimeout(()=>{
							uni.navigateBack()
						},3000)
					}
				}
			},

			onOpenScan() {

			},


			gotoAuthTiktok() {
				// #ifdef APP-PLUS
				var ext = {
					"appid": dyclientId,
					"checked_scope": "data.external.item",
					// "unchecked_scope": "",
					// "scope" : "user_info" //data.external.item, video.list.bind,video.data
				}
				plugin.ssoLogin(ext, (res) => {
					console.log(res)
					if (res.finished && res.code) {
						that.authTiktok(res.code)
					}
				})
				// #endif
			},


			authTiktok(code) {
				let that = this
				// console.log("authTiktok",code)
				api.authTiktok({
					param: {
						code: code,
					}
				}).then(res => {
					console.log("authTiktok", res)
					if (res.success) {
						that.getUserInfo()
					}
				})
			},

			getUserInfo() {
				api.getUserInfo().then(res => {
					console.log("getUserInfo", res)
					if (res.success) {
						that.setUserInfo(res.data)
						uni.navigateBack()
					}
				}).catch(err => {

				})
			},

			//上传图片
			uploadImge(file) {
				const that = this
				uni.saveImageToPhotosAlbum({
					filePath: url,
					success() {
						
					}
				})
				
				
				// uni.uploadFile({
				// 	url: that.$API_URL + 'index/upload', //仅为示例，非真实的接口地址
				// 	filePath: file,
				// 	name: 'file',
				// 	formData: {
				// 		'user': 'test'
				// 	},
				// 	success: res => {
				// 		let data = JSON.parse(res.data)
				// 		if (res.statusCode == 200 && data.code == '1') {
				// 			// that.msg(data.msg || '上传成功');
				// 			that.image = data.data.url;
				// 			console.log(that.image)

				// 		}
				// 	},

				// })

			},

			// 截屏绘制
			captureWebview() {
				let _this = this
				console.log('截屏绘制')
				this.bitmap = new plus.nativeObj.Bitmap('test');
				// 将webview内容绘制到Bitmap对象中
				let rand = Math.floor(Math.random() * 10000)
				let saveUrl = '_doc/' + rand + 'order.jpg'
				_this.ws.draw(_this.bitmap, function() {
					_this.bitmap.save(saveUrl, {}, function(i) {
						uni.saveImageToPhotosAlbum({
							filePath: saveUrl,
							success: function() {
								uni.showToast({
									title: '保存成功',
									icon: 'none'
								})
								_this.bitmap.clear();
								_this.openScan()
							}
						});
						console.log('保存图片成功：' + JSON.stringify(i));
					})
					console.log('截屏绘制图片成功', _this.bitmap);
				}, function(e) {
					uni.hideLoading()
					console.log('截屏绘制图片失败：' + JSON.stringify(e));
				});
			},

			openScan(types) {
				var url = "snssdk1128://scan"
				plus.runtime.openURL(url, function(res) {
					console.log("openURL:", res);
				});
			},
		}
	}
</script>

<style>
	page {
		background-color: #f8f8f8;
	}
</style>

<style lang="scss">
	.webview {

	}

	.functionItem {
		width: 750rpx;
		height: 100rpx;
		background-color: #ffffff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 1px;
		z-index: 99999;
		position: fixed;
		bottom: 0;
		left: 0;

		.left {
			font-size: 30rpx;
			color: #333333;
			margin-left: 40rpx;
			display: flex;
			align-items: center;

			.icon {
				width: 40rpx;
				height: 40rpx;
				// margin-left: 30rpx;
				margin-right: 30rpx;
			}
		}

		.right {
			display: flex;
			align-items: center;
			font-size: 30rpx;
			color: #999999;
			margin-right: 40rpx;

			.image {
				width: 16rpx;
				height: 22rpx;
				margin-left: 33rpx;
			}
		}
	}
</style>